<template>
  <div>
    <div v-if="showReview">
      <card>
        <div slot="header" >
          <cell 
          :title="'原成绩：正确'+correctCount+'题,用时'+((totalTime>60)?parseInt(totalTime/60)+'分钟':totalTime+'秒')"
          >
            <span style="font-size:0.9em">{{exerciseStatus}}</span>
          </cell>
        </div >
        <div slot="content">
          <x-progress :percent="index+1" :show-cancel="false"></x-progress>
          <p style="padding:15px" v-text="questionArray[index].question"></p>
          <checklist
            :options="questionArray[index].content"
            :max="maxSelect"
            required
            v-model="questionArray[index].checkedOption"
          ></checklist> 
        </div>
        <div slot="footer" style="margin:15px">
          <x-table :cell-bordered="false">
            <tr>
              <td style="width:50%">
                <check-icon :value.sync="displayAnswer" type="plain">显示答案</check-icon>
              </td>
              <td  style="width:50%;text-align:left">
                <span v-show="displayAnswer" style="font-weight: bold;color:#00ce34">
                  <span v-text="questionArray[index].answer"></span>
                </span>
              </td>
            </tr>
            <tr>
              <td>
                <check-icon :value.sync="showResult" type="plain">即时判题</check-icon>
              </td>
              <td style="width:50%;text-align:left">
                <span v-show="showResult">
                  <span v-if="questionArray[index].answer === questionArray[index].checkedOption[0]"> 
                        <label class="correctStyle">回答正确</label>
                  </span>
                  <span v-else>
                        <label class="wrongStyle">未答或错误</label>
                  </span> 
                </span>
              </td>
            </tr>
          </x-table>
          <div style="margin-top:20px">
            <flexbox>
              <flexbox-item>
                <x-button  
                  type="primary"
                  text="上一题"
                  @click.native="getPrevious"
                  plain
                ></x-button>
              </flexbox-item>
              <flexbox-item>
                <x-button 
                  type="warn"
                  text="返回"
                  @click.native="goBackList"
                ></x-button>
              </flexbox-item>
              <flexbox-item>
                <x-button 
                  type="primary"
                  text="下一题"
                  @click.native="getNext"
                ></x-button>
              </flexbox-item>
            </flexbox>
          </div>
        </div>
      </card>
    </div>
    <div v-if="showList">
      <x-header :left-options="{showBack: false}" v-if="showTimeOut">做题记录</x-header>
      <p style="text-align:center;font-size:0.8em;color:red">本历史记录保存{{$store.state.MAX_HISTORY_DAYS*(-1)}}天，最多保存{{$store.state.MAX_HISTORY_COUNT}}条，请及时复习。</p>
      <x-table slot="content">
        <tr>
          <th>序号</th>
          <th>日期</th>
          <th>正确</th>
          <th>用时</th>
          <th>正确率</th>
        </tr>
        <template v-for="(item, index) in exerciseHistory">
          <tr v-bind:key="index">
            <td>{{index+1}}</td>
            <td><span @click="getReview(index)" style="color:#04BE02">{{item.key.substring(2)}}</span></td>
            <td>{{JSON.parse(item.value).correctCount}}</td>
            <td>{{JSON.parse(item.value).totalTime>60?parseInt(JSON.parse(item.value).totalTime/60)+'分钟':JSON.parse(item.value).totalTime+'秒'}}</td>
            <td>{{JSON.parse(item.value).successRate}}%</td>
          </tr>
        </template>
      </x-table>
      <div style="margin:10px">
        <flexbox>
          <flexbox-item :span="6">
            <div class="buttonCenter">
              <x-button plain type="primary" mini  link="/select-user-card">继续练习</x-button>              
            </div>
          </flexbox-item>
          <flexbox-item :span="6">
            <div class="buttonCenter">
              <x-button plain  type="default" mini @click.native="clearHistory">清除记录</x-button>
            </div>
          </flexbox-item>
        </flexbox>
      </div>    
    </div>
  </div>  
</template>
<script>
import {
  Cell,
  XHeader,
  Group,
  Checklist,
  Toast,
  CheckIcon,
  Clocker,
  Card,
  Flexbox,
  FlexboxItem,
  XButton,
  Icon,
  XProgress,
  XTable,
  Panel
} from 'vux'
import { mapGetters, mapActions } from 'vuex'

export default {
  components: {
    Cell,
    XHeader,
    Group,
    Checklist,
    Toast,
    CheckIcon,
    Clocker,
    Card,
    Flexbox,
    FlexboxItem,
    XButton,
    Icon,
    XProgress,
    XTable,
    Panel
  },
  data () {
    return {
      showReview: false,
      showList: true,
      exerciseHistory: [],
      questionArray: [],
      index: 0,
      maxSelect: 1,
      successRate: 0,
      displayAnswer: true, // 显示答案
      showResult: true, // 是否即时显示对错
      showDisplayAnswerCheckIcon: true, // 显示“显示答案开关”
      historyCount: 0,  // 历史记录总数
      historyKeyRecord: [], // 历史记录key的数组
      correctCount: 0, // 正确的个数
      totalTime: 0,  // 用时
      currentUserID: 2,
      showTimeOut: false

    }
  },
  computed: {
    ...mapGetters(['getQuestionCode']),
    // 显示正确答案
    answer: function () {
      if (this.displayAnswer) {
        return '正确答案：' + this.questionArray[this.index].answer
      }
    },

    // 剩余题目
    lastQuestionCount: function () {
      var amount = this.$store.state.sysconfig.ExerciseQuestionAmount
      var index = this.index
      return amount - index - 1
    },

    // 做题进度
    exerciseStatus: function () {
      var qtype = this.questionArray[this.index].questionType === this.getQuestionCode('选择题') ? '选择题' : '判断题'
      return '[' + qtype + '][' + (this.index + 1) + '/' + this.lastQuestionCount + ']'
    }
  },
  methods: {
    ...mapActions(['reviewExercises']),
    // 开始查看历史记录
    getReview: function (index) {
      // 题目信息
      this.questionArray = JSON.parse(this.exerciseHistory[index].value).question
      // 练习正确率
      this.successRate = JSON.parse(this.exerciseHistory[index].value).successRate
      // 做题正确个数
      this.correctCount = JSON.parse(this.exerciseHistory[index].value).correctCount
      // 做题用时
      this.totalTime = JSON.parse(this.exerciseHistory[index].value).totalTime
      // console.log(this.exerciseHistory[index].value)
      this.showReview = true
      this.showList = false
    },

    // 返回列表
    goBackList: function () {
      this.showReview = false
      this.showList = true
    },

    // 下一题操作
    getNext: function () {
      if (this.index < this.$store.state.sysconfig.ExerciseQuestionAmount) {
        this.index = this.index + 1
      }
    },

    // 前一题操作
    getPrevious: function () {
      if (this.index > 0) {
        this.index = this.index - 1
      }
    },

    // 获得历史记录
    getHistory: function () {
      for (let i = 0; i < localStorage.length; i++) {
        var startIndex = localStorage.key(i).indexOf('E-20')
        if (startIndex === 0) {
          var key = localStorage.key(i)
          var value = localStorage.getItem(localStorage.key(i))
          this.exerciseHistory.push({'key': key, 'value': value})
        }
      }
    },

    // 清除历史记录
    clearHistory: function () {
      var that = this
      this.$vux.confirm.show({
        title: '确认',
        content: '清除的历史记录将不能被恢复，您确认要清除历史记录？',
        onConfirm: () => {
          var keyArray = []
          for (let i = 0; i < localStorage.length; i++) {
            var startIndex = localStorage.key(i).indexOf('E-20')
            if (startIndex === 0) {
              keyArray.push(localStorage.key(i))
            }
          }
          for (let i = 0; i < keyArray.length; i++) {
            localStorage.removeItem(keyArray[i])
          }
          that.$router.push({name: 'Home'})
        }
      })
    }
  },
  mounted () {
    setTimeout(() => {
      this.showTimeOut = true
    }, 500)

    this.reviewExercises()
    this.deleteExpiryHistory()
    this.deleteLimitedHistory()
    // 获取做题记录
    this.getHistory()
  }

}
</script>
<style scoped>
.buttonCenter{
  text-align: center;
}
.correctStyle{
  padding-top: 0px;
  padding-bottom: 2px;
  padding-left: 3px;
  padding-right: 3px;
  border-radius: 5%;
  border:1px solid #ffffff;
  background-color: #179b16;
  color: #FFF;
}
.wrongStyle{
  padding-top: 0px;
  padding-bottom: 2px;
  padding-left: 3px;
  padding-right: 3px;
  border-radius: 5%;
  border:1px solid #ffffff;
  background-color:#e64304;
  color: #FFF;
}
</style>
